package com.xs.store.zuul.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 限流(目前只对订单) 可以学习下谷歌的gauva框架
 * 限流方式:nginx限流，网关层限流 一般是nginx与网关一起用，
 * nginx（可能会挂，采用nginx+lvs负载均衡+keepalive）
 * 第一步访问网关集群限流，
 */
@Component
public class RateLimeiterFilter extends ZuulFilter {

    //每秒产生1000个令牌
    private static final RateLimiter RATE_LIMITER=RateLimiter.create(1000);

    @Override
    public String filterType() {
        return  PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -4;
    }

    /**
     * 订单限流
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest httpRequest= requestContext.getRequest();
        //httpRequest.getRequestURI();//请求的路径除了域名之外的
        // httpRequest.getRequestURL();//整个地址

        //订单限流
        if("/order/list".equalsIgnoreCase(httpRequest.getRequestURI())){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();
        //限流
        if(!RATE_LIMITER.tryAcquire()){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
        }
        return null;
    }
}
